#include "server.hpp"


// 管理所有的连接
std::unordered_map<uint64_t, PtrConnection> _conns;
// EventLoop loop;
uint64_t conn_id = rand() % 10000;

void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
    // conn->Shutdown();
}

void Acceptor(EventLoop *loop, Channel *lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    if (newfd < 0)
    {
        return;
    }
    conn_id++;
    PtrConnection conn(new Connection(loop, conn_id, newfd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10); // 启动非活跃超时销毁
    conn->Established();             // 就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW ---------------");
}
int main()
{
    srand(time(NULL));
    EventLoop loop;
    Socket lst_sock;
    lst_sock.CreateServer(8500);

    Channel lst_channel(&loop, lst_sock.Fd());
    lst_channel.SetReadCallback(std::bind(Acceptor, &loop, &lst_channel));
    lst_channel.EnableRead();
    while (1)
    {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}
